﻿namespace OboutInc.Flyout2
{
    using OboutInc.Flyout2.Effects;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;

    [Designer(typeof(FlyoutDesigner)), DefaultProperty("Flyout"), ToolboxData("<{0}:Flyout runat=\"server\">[Flyout]</{0}:Flyout>")]
    public class Flyout : Control, INamingContainer
    {
        private ScriptManagerHelper myScriptManager;
        private string myVersion = "2.0.5.0";
        private bool ScriptResourceRendered;

        public Flyout()
        {
            this.ViewState["targetid"] = "";
            this.ViewState["opentime"] = 200;
            this.ViewState["closetime"] = 200;
            this.ViewState["resolution"] = 10;
            this.ViewState["left"] = 0;
            this.ViewState["top"] = 0;
            this.ViewState["delaytime"] = 200;
            this.ViewState["opacity"] = 100;
            this.ViewState["position"] = PositionStyle.BOTTOM_CENTER;
            this.ViewState["align"] = AlignStyle.MIDDLE;
            this.ViewState["openevent"] = OpenEvents.ONMOUSEOVER;
            this.ViewState["closeevent"] = CloseEvents.ONMOUSEOUT;
            this.ViewState["openeffects"] = new ArrayList();
            this.ViewState["closeeffects"] = new ArrayList();
            this.ViewState["dragpanels"] = new ArrayList();
            this.ViewState["zindex"] = 0;
            this.ViewState["onclientclose"] = "";
            this.ViewState["onclientopen"] = "";
            this.ViewState["onclientinit"] = "";
            this.ViewState["flyingeffect"] = FlyingEffectStyle.NONE;
            this.ViewState["slidingeffect"] = SlidingEffectStyle.NONE;
            this.ViewState["fadingeffect"] = false;
            this.ViewState["noneeffect"] = false;
            this.ViewState["slidingrange"] = 10;
            this.ViewState["IsModal"] = false;
            this.ViewState["PageOpacity"] = 0x19;
            this.ViewState["PageColor"] = "#DDDDDD";
            this.ViewState["DebugMode"] = true;
            this.ViewState["ClearType"] = false;
        }

        private bool CheckAjaxPageInheritance()
        {
            Type baseType = this.Page.GetType().BaseType;
            while (baseType != null)
            {
                if (baseType.ToString() == "OboutInc.oboutAJAXPage")
                {
                    return true;
                }
                try
                {
                    baseType = Activator.CreateInstance(baseType).GetType().BaseType;
                    continue;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }

        private string createscript(string realID, string attachto, bool lastobj, bool inscript)
        {
            StringBuilder builder = new StringBuilder();
            if (inscript)
            {
                builder.Append("<script type='text/javascript' >");
            }
            builder.AppendFormat("var {0};", realID.ToString());
            builder.AppendFormat("function init{0}(attempt)", realID.ToString());
            builder.Append("{");
            builder.Append("try");
            builder.Append("{");
            builder.AppendFormat("if(typeof __flyoutGlobal.styleTopMargin == 'undefined')__flyoutGlobal.executeMargins();{0}=new Flyout2(", realID.ToString());
            builder.AppendFormat("'{0}'", realID.ToString());
            builder.Append(",");
            string id = "";
            if ((attachto.IndexOf("[") > 0) && (attachto.IndexOf("]") > 0))
            {
                string str2 = attachto;
                int index = str2.IndexOf("[");
                int num2 = str2.IndexOf("]");
                attachto = str2.Substring(index + 1, (num2 - index) - 1);
                id = str2.Substring(0, index);
            }
            if (attachto != string.Empty)
            {
                object obj2 = this.findControl(this.NamingContainer, attachto);
                if (obj2 != null)
                {
                    attachto = ((Control) obj2).ClientID;
                }
            }
            builder.AppendFormat("'{0}'", attachto);
            builder.Append(",");
            if (id != "")
            {
                object obj3 = this.findControl(this.NamingContainer, id);
                if (obj3 != null)
                {
                    builder.AppendFormat("'{0}'", ((Control) obj3).ClientID);
                }
            }
            builder.AppendFormat("'{0}'", id);
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.ClientID + "_content");
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.Position);
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.Align);
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.OpenEvent);
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.CloseEvent);
            builder.Append(",");
            builder.AppendFormat("{0}", this.OpenTime.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.CloseTime.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.DelayTime.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.Resolution.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.RelativeLeft.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.RelativeTop.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.Opacity.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.zIndex.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", lastobj.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("{0}", this.DebugMode.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("{0}", this.IsModal.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("{0}", this.ClearType.ToString().ToLower());
            builder.Append(",");
            builder.AppendFormat("'{0}'", this.PageColor.ToString());
            builder.Append(",");
            builder.AppendFormat("{0}", this.PageOpacity.ToString());
            builder.Append(");");
            builder.AppendFormat("if ({0}.removeOCB!=null)", realID);
            builder.Append("{");
            if (this.OpenEffects.Count > 0)
            {
                for (int j = 0; j < this.OpenEffects.Count; j++)
                {
                    builder.AppendFormat("{0}.registerOpenEffect({1});", realID, ((Effect) this.OpenEffects[j]).renderInit());
                }
            }
            else
            {
                builder.AppendFormat("{0}.registerOpenEffect({1});", realID, new Flying(FlyingEffectStyle.MIDDLE_CENTER).renderInit());
            }
            if (this.CloseEffects.Count > 0)
            {
                for (int k = 0; k < this.CloseEffects.Count; k++)
                {
                    builder.AppendFormat("{0}.registerCloseEffect({1});", realID, ((Effect) this.CloseEffects[k]).renderInit());
                }
            }
            else
            {
                builder.AppendFormat("{0}.registerCloseEffect({1});", realID, new Flying(FlyingEffectStyle.MIDDLE_CENTER).renderInit());
            }
            for (int i = 0; i < this.DragPanels.Count; i++)
            {
                builder.AppendFormat("{0}.rDP('{1}','{2}',{3},'{4}');", new object[] { realID, ((DragPanel) this.DragPanels[i]).getClientID(), ((DragPanel) this.DragPanels[i]).getClientID() + attachto, ((DragPanel) this.DragPanels[i]).DraggingOpacity, ((DragPanel) this.DragPanels[i]).Cursor });
            }
            builder.Append("}");
            builder.Append("}");
            builder.Append("catch(e)");
            builder.Append("{");
            if (this.DebugMode)
            {
                builder.AppendFormat("alert(\"Failed to initialize [{0}] \\n.Error:\"+ e+ \"\\nPlease contact support@obout.com for support.\");", this.ID);
            }
            builder.Append("}");
            if (((this.OnClientInit != "") || (this.OnClientOpen != "")) || (this.OnClientClose != ""))
            {
                builder.Append("try");
                builder.Append("{");
                if (this.OnClientInit != "")
                {
                    if (this.OnClientInit.IndexOf("function") == 0)
                    {
                        builder.AppendFormat("{0}.OnInit={1};", realID, this.OnClientInit);
                    }
                    else
                    {
                        builder.AppendFormat("{0}.OnInit=function()", realID);
                        builder.Append("{");
                        builder.Append(this.OnClientInit);
                        builder.Append("};");
                    }
                }
                if (this.OnClientOpen != "")
                {
                    if (this.OnClientOpen.IndexOf("function") == 0)
                    {
                        builder.AppendFormat("{0}.OnOpen={1};", realID, this.OnClientOpen);
                    }
                    else
                    {
                        builder.AppendFormat("{0}.OnOpen=function()", realID);
                        builder.Append("{");
                        builder.Append(this.OnClientOpen);
                        builder.Append("};");
                    }
                }
                if (this.OnClientClose != "")
                {
                    if (this.OnClientClose.IndexOf("function") == 0)
                    {
                        builder.AppendFormat("{0}.OnClose={1};", realID, this.OnClientClose);
                    }
                    else
                    {
                        builder.AppendFormat("{0}.OnClose=function()", realID);
                        builder.Append("{");
                        builder.Append(this.OnClientClose);
                        builder.Append("};");
                    }
                }
                builder.Append("}");
                builder.Append("catch(ex)");
                builder.Append("{");
                builder.Append("alert('Error:'+ex);");
                builder.Append("}");
            }
            builder.Append("}");
            if (this.myScriptManager.isAjax)
            {
                builder.AppendFormat("init{0}(1);", realID.ToString());
            }
            else
            {
                builder.AppendFormat("old{0}load = window.onload;", realID.ToString());
                builder.Append("window.onload=function(evt)");
                builder.Append("{");
                builder.AppendFormat("if (old{0}load!=null) old{0}load();", realID.ToString());
                builder.AppendFormat("init{0}(0);", realID.ToString());
                builder.Append("};");
            }
            if (inscript)
            {
                builder.Append("</script> ");
            }
            return builder.ToString();
        }

        private object findControl(Control where, string id)
        {
            if (where != null)
            {
                foreach (Control control in where.Controls)
                {
                    if ((control.ID == id) || (id == ""))
                    {
                        return control;
                    }
                    if (control.HasControls())
                    {
                        object obj2 = this.findControl(control, id);
                        if (obj2 != null)
                        {
                            return obj2;
                        }
                    }
                }
            }
            return null;
        }

        public string getClientID()
        {
            ArrayList list = this.seperateIDs(this.AttachTo);
            if (list.Count <= 0)
            {
                return this.ClientID;
            }
            return (this.ClientID + this.getcorrectAttachTo((string) list[0]));
        }

        public string getClientID(string AttachToID)
        {
            AttachToID = AttachToID.Trim();
            ArrayList list = this.seperateIDs(this.AttachTo);
            for (int i = 0; i < list.Count; i++)
            {
                if (AttachToID == ((string) list[i]))
                {
                    return (this.ClientID + this.getcorrectAttachTo((string) list[i]));
                }
            }
            return this.ClientID;
        }

        private string getcorrectAttachTo(string tmp)
        {
            if ((tmp.IndexOf("[") > 0) && (tmp.IndexOf("]") > 0))
            {
                int index = tmp.IndexOf("[");
                int num2 = tmp.IndexOf("]");
                return tmp.Substring(index + 1, (num2 - index) - 1);
            }
            return tmp;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.myScriptManager = new ScriptManagerHelper(this);
            string webResourceUrl = this.Page.ClientScript.GetWebResourceUrl(base.GetType(), "OboutInc.Flyout2.script.flyout2.min.js");
            if (!this.myScriptManager.isAjax && !this.CheckAjaxPageInheritance())
            {
                webResourceUrl = webResourceUrl.Replace("&", "&amp;");
            }
            if (!this.myScriptManager.isAjax || !this.myScriptManager.IsInAsyncCallback)
            {
                this.ScriptResourceRendered = this.RegisterScriptResource(webResourceUrl);
            }
        }

        internal string registerDragPanel(DragPanel dp)
        {
            ((ArrayList) this.ViewState["dragpanels"]).Add(dp);
            int num = ((ArrayList) this.ViewState["dragpanels"]).Count - 1;
            return (this.ClientID + "_dnd_" + num.ToString());
        }

        public bool RegisterScriptResource(string url)
        {
            if (this.Page.Form == null)
            {
                return false;
            }
            HtmlHead header = this.Page.Header;
            ScriptManagerHelper helper = new ScriptManagerHelper(this);
            if (header == null)
            {
                try
                {
                    helper.RegisterClientScriptInclude(this, "RegisterScriptReference", url);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            bool flag = true;
            foreach (Control control in header.Controls)
            {
                HtmlGenericControl control2 = control as HtmlGenericControl;
                if ((control2 != null) && url.Equals(control2.Attributes["src"], StringComparison.OrdinalIgnoreCase))
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                try
                {
                    HtmlGenericControl child = new HtmlGenericControl("script");
                    child.Attributes.Add("type", "text/javascript");
                    child.Attributes.Add("src", url);
                    child.Attributes.Add("id", "jorra1");
                    header.Controls.Add(child);
                }
                catch
                {
                    try
                    {
                        helper.RegisterClientScriptInclude(this, "RegisterScriptReference", url);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            bool flag = true;
            this.myScriptManager = new ScriptManagerHelper(this);
            ArrayList list = this.seperateIDs(this.AttachTo);
            try
            {
                this.Page.VerifyRenderingInServerForm(this);
            }
            catch
            {
                flag = false;
            }
            writer.Write("\n\n<!-- obout Flyout v." + this.myVersion + "  http://www.obout.com  -->\n\n");
            writer.WriteBeginTag("div");
            writer.WriteAttribute("id", this.ClientID + "_content");
            writer.WriteAttribute("style", "display:none;filter:alpha(opacity=0);-moz-opacity:0;opacity:0;");
            writer.Write(">");
            base.Render(writer);
            writer.WriteEndTag("div");
            writer.Write("<div id=\"{0}\"></div>", this.ClientID + "_contentbox");
            if (!this.ScriptResourceRendered)
            {
                string webResourceUrl = this.Page.ClientScript.GetWebResourceUrl(base.GetType(), "OboutInc.Flyout2.script.flyout2.min.js");
                if (!this.myScriptManager.isAjax && !this.CheckAjaxPageInheritance())
                {
                    webResourceUrl = webResourceUrl.Replace("&", "&amp;");
                }
                writer.Write("<script type=\"text/javascript\" src=\"" + webResourceUrl + "\" id=\"jorra3\"></script>");
                this.ScriptResourceRendered = true;
            }
            if (this.FadingEffect)
            {
                this.OpenEffects.Add(new Fading());
                this.CloseEffects.Add(new Fading());
            }
            if (this.NoneEffect)
            {
                this.OpenEffects.Add(new None());
                this.CloseEffects.Add(new None());
            }
            if (this.SlidingEffect != SlidingEffectStyle.NONE)
            {
                this.OpenEffects.Add(new Sliding(this.SlidingEffect, this.SlidingRange));
                this.CloseEffects.Add(new Sliding(this.SlidingEffect, this.SlidingRange));
            }
            if (this.FlyingEffect != FlyingEffectStyle.NONE)
            {
                this.OpenEffects.Add(new Flying(this.FlyingEffect));
                this.CloseEffects.Add(new Flying(this.FlyingEffect));
            }
            for (int i = 0; i < list.Count; i++)
            {
                string realID = this.ClientID + this.getcorrectAttachTo((string) list[i]);
                if (!flag || this.CheckAjaxPageInheritance())
                {
                    writer.Write(this.createscript(realID, (string) list[i], i == (list.Count - 1), true));
                }
                else
                {
                    this.myScriptManager.RegisterStartupScript(this, realID, this.createscript(realID, (string) list[i], i == (list.Count - 1), false), true);
                }
            }
        }

        private ArrayList seperateIDs(string textIDs)
        {
            ArrayList list = new ArrayList();
            int length = 1;
            while (length > 0)
            {
                length = textIDs.LastIndexOf(",");
                string str = textIDs.Substring(length + 1);
                textIDs = (length > 0) ? textIDs.Substring(0, length) : textIDs;
                list.Add(str.Trim().Trim());
            }
            return list;
        }

        [Category("Layout"), Description("Gets or sets the Alignment with AttachTo element. ")]
        public virtual AlignStyle Align
        {
            get
            {
                return (AlignStyle) this.ViewState["align"];
            }
            set
            {
                this.ViewState["align"] = value;
            }
        }

        [Category("Initiation"), Description("Gets or sets ID of the element which Flyout will be attached to.")]
        public virtual string AttachTo
        {
            get
            {
                return (string) this.ViewState["targetid"];
            }
            set
            {
                this.ViewState["targetid"] = value;
            }
        }

        [Description("ClearType"), Category("ClearType")]
        public virtual bool ClearType
        {
            get
            {
                return (bool) this.ViewState["ClearType"];
            }
            set
            {
                this.ViewState["ClearType"] = value;
            }
        }

        [Browsable(false)]
        private ArrayList CloseEffects
        {
            get
            {
                return (ArrayList) this.ViewState["closeeffects"];
            }
            set
            {
                this.ViewState["closeeffects"] = value;
            }
        }

        [Category("Behavior"), Description("Gets or sets the close event type of flyout")]
        public virtual CloseEvents CloseEvent
        {
            get
            {
                return (CloseEvents) this.ViewState["closeevent"];
            }
            set
            {
                this.ViewState["closeevent"] = value;
            }
        }

        [Description("Gets or sets the time Flyout between when flyout open and when flyout fully close"), Category("Behavior")]
        public virtual int CloseTime
        {
            get
            {
                return (int) this.ViewState["closetime"];
            }
            set
            {
                this.ViewState["closetime"] = value;
            }
        }

        [Description("Gets or sets whether Flyout is on Debug Mode.")]
        public virtual bool DebugMode
        {
            get
            {
                return (bool) this.ViewState["DebugMode"];
            }
            set
            {
                this.ViewState["DebugMode"] = value;
            }
        }

        [Description("Gets or sets the delay time which is how long FlyBox will wait before closing when user move mouse out of Flyout."), Category("Behavior")]
        public virtual int DelayTime
        {
            get
            {
                return (int) this.ViewState["delaytime"];
            }
            set
            {
                this.ViewState["delaytime"] = value;
            }
        }

        [Browsable(false)]
        public virtual ArrayList DragPanels
        {
            get
            {
                return (ArrayList) this.ViewState["dragpanels"];
            }
            set
            {
                this.ViewState["dragpanels"] = value;
            }
        }

        [Category("Effects"), Description("Gets or sets whether Fading effect is on.")]
        public virtual bool FadingEffect
        {
            get
            {
                return (bool) this.ViewState["fadingeffect"];
            }
            set
            {
                this.ViewState["fadingeffect"] = value;
            }
        }

        [Category("Effects"), Description("Gets or sets type of FlyingEffect.")]
        public virtual FlyingEffectStyle FlyingEffect
        {
            get
            {
                return (FlyingEffectStyle) this.ViewState["flyingeffect"];
            }
            set
            {
                this.ViewState["flyingeffect"] = value;
            }
        }

        [Description("Get or set whether Flyotu shown in modal mode"), Category("IsModal")]
        public virtual bool IsModal
        {
            get
            {
                return (bool) this.ViewState["IsModal"];
            }
            set
            {
                this.ViewState["IsModal"] = value;
            }
        }

        [Category("Effects"), Description("Gets or sets whether no effect is used.")]
        public virtual bool NoneEffect
        {
            get
            {
                return (bool) this.ViewState["noneeffect"];
            }
            set
            {
                this.ViewState["noneeffect"] = value;
            }
        }

        [Description("Set function for Close event"), Category("Behavior")]
        public virtual string OnClientClose
        {
            get
            {
                return (string) this.ViewState["onclientclose"];
            }
            set
            {
                this.ViewState["onclientclose"] = value.Trim();
            }
        }

        [Description("Set function for Init event"), Category("Behavior")]
        public virtual string OnClientInit
        {
            get
            {
                return (string) this.ViewState["onclientinit"];
            }
            set
            {
                this.ViewState["onclientinit"] = value.Trim();
            }
        }

        [Category("Behavior"), Description("Set function for Open event")]
        public virtual string OnClientOpen
        {
            get
            {
                return (string) this.ViewState["onclientopen"];
            }
            set
            {
                this.ViewState["onclientopen"] = value.Trim();
            }
        }

        [Description("Gets or sets the Opacity "), Category("Layout")]
        public virtual int Opacity
        {
            get
            {
                return (int) this.ViewState["opacity"];
            }
            set
            {
                this.ViewState["opacity"] = value;
            }
        }

        [Browsable(false)]
        private ArrayList OpenEffects
        {
            get
            {
                return (ArrayList) this.ViewState["openeffects"];
            }
            set
            {
                this.ViewState["openeffects"] = value;
            }
        }

        [Description("Gets or sets the open event type of flyout"), Category("Behavior")]
        public virtual OpenEvents OpenEvent
        {
            get
            {
                return (OpenEvents) this.ViewState["openevent"];
            }
            set
            {
                this.ViewState["openevent"] = value;
            }
        }

        [Category("Behavior"), Description("Gets or sets the time Flyout need to open.")]
        public virtual int OpenTime
        {
            get
            {
                return (int) this.ViewState["opentime"];
            }
            set
            {
                this.ViewState["opentime"] = value;
            }
        }

        [Category("Layout"), Description("Gets or sets the PageColor ")]
        public virtual string PageColor
        {
            get
            {
                return (string) this.ViewState["PageColor"];
            }
            set
            {
                this.ViewState["PageColor"] = value;
            }
        }

        [Category("Layout"), Description("Gets or sets the PageOpacity ")]
        public virtual int PageOpacity
        {
            get
            {
                return (int) this.ViewState["PageOpacity"];
            }
            set
            {
                this.ViewState["PageOpacity"] = value;
            }
        }

        [Description("Gets or sets the built-in common used relative postion of Flyout to position of AttachTo element."), Category("Layout")]
        public virtual PositionStyle Position
        {
            get
            {
                return (PositionStyle) this.ViewState["position"];
            }
            set
            {
                this.ViewState["position"] = value;
            }
        }

        [Category("Layout"), Description("Gets or sets relative Left of Flyout to Left of AttachTo element when Position is ABSOLUTE.")]
        public virtual int RelativeLeft
        {
            get
            {
                return (int) this.ViewState["left"];
            }
            set
            {
                this.ViewState["left"] = value;
            }
        }

        [Description(" Gets or sets relative LTop of Flyout to Top of AttachTo element when Position is ABSOLUTE."), Category("Layout")]
        public virtual int RelativeTop
        {
            get
            {
                return (int) this.ViewState["top"];
            }
            set
            {
                this.ViewState["top"] = value;
            }
        }

        [Description("Gets or sets resolution which is how many frame Flyout will draw when openning. The higher value the smoother."), Category("Behavior")]
        public virtual int Resolution
        {
            get
            {
                return (int) this.ViewState["resolution"];
            }
            set
            {
                this.ViewState["resolution"] = value;
            }
        }

        [Category("Effects"), Description("Gets or sets type of Sliding Effect .")]
        public virtual SlidingEffectStyle SlidingEffect
        {
            get
            {
                return (SlidingEffectStyle) this.ViewState["slidingeffect"];
            }
            set
            {
                this.ViewState["slidingeffect"] = value;
            }
        }

        [Category("Effects"), Description("Gets or sets the SlidingRange effect.")]
        public virtual int SlidingRange
        {
            get
            {
                return (int) this.ViewState["slidingrange"];
            }
            set
            {
                this.ViewState["slidingrange"] = value;
            }
        }

        [Category("Layout"), Description("Gets or sets the zIndex of Flyout.")]
        public virtual int zIndex
        {
            get
            {
                return (int) this.ViewState["zindex"];
            }
            set
            {
                this.ViewState["zindex"] = value;
            }
        }
    }
}

